package work4.work2;

import java.awt.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class FileDownLoad {
    static  public void openNetFile(String url,String fileName,String savePath){
        try {
            File file = new File(savePath);
            if(!file.exists()){
                file.mkdirs();
            }

            URL FileUrl=new URL(url);
            URLConnection connection =(HttpURLConnection) FileUrl.openConnection();
            connection.setConnectTimeout(3*1000);
            InputStream inputStream = connection.getInputStream();
            String downFile=file.getPath()+"\\"+fileName;
            OutputStream os=new FileOutputStream(downFile);

            byte[] buffer = new byte[1024*1024*5];int len;
            while ((len=inputStream.read(buffer))!=-1){
                os.write(buffer,0,len);
            }


            System.out.println("下载成功");
            Desktop.getDesktop().open(new File(downFile));

        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }catch(NullPointerException e){

        }

    }
}
